#include "publictool.h"
#include "messagetips.h"

#include <QDebug>
#include <QHeaderView>
#include <QFileDialog>
#include <QLabel>
#include <QMessageBox>

PublicTool::PublicTool()
{

}

QByteArray PublicTool::QPixmapToQByteArray(const QPixmap &pixmap) {

    QByteArray byteArray;
    QBuffer buffer(&byteArray);
    buffer.open(QIODevice::WriteOnly);

    QImage image = pixmap.toImage(); // 将 QPixmap 转换为 QImage
    if (!image.isNull()) {
        image.save(&buffer, "PNG"); // 将 QImage 保存为 PNG 格式的 QByteArray
    }

    buffer.close();
    return byteArray;
}

QPixmap PublicTool::QByteArrayToQPixmap(const QByteArray &imageData) {
    QPixmap pixmap;
    if (!pixmap.loadFromData(imageData)) {
        qDebug() << "Failed to load QPixmap from QByteArray";
        return QPixmap();
    }
    return pixmap;
}

void PublicTool::setTableHead(QTableWidget *wgt, QStringList head)
{
    wgt->setColumnCount(head.count());

    wgt->setHorizontalHeaderLabels(head);
    wgt->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

    setTableInit(wgt);
}

void PublicTool::setTableInit(QTableWidget *wgt)
{
    wgt->setEditTriggers(QAbstractItemView::NoEditTriggers);

}

QString PublicTool::openCSVSaveDialog(QString name)
{
    return QFileDialog::getSaveFileName(nullptr, "CSV file",name,"Files (*.csv)");
}

QString PublicTool::openCSVOpenDialog()
{
    return QFileDialog::getOpenFileName(nullptr, "CSV file","","Files (*.csv)");
}

void PublicTool::showErr(const QString &err)
{
    MessageTips *mMessageTips = new MessageTips(err);
    mMessageTips->show();
}

void PublicTool::showEarlyWarning(QString str)
{

//    auto s = QString("\t\t\t\t\t\n%1\n").arg(str);

    auto temp = QString("<font  color='red'>%1</font>").arg(str);
    QMessageBox::critical(nullptr,"预警信息",temp);
//    MessageTips *msg = new MessageTips(str);
//    msg->setShowTime(5);
    //    msg->show();
}

void PublicTool::showEarlyWarning(QList<DB_View_StudentInfo> stus, QString app)
{

    QStringList infos;


    for(auto && stu:stus){
        if(stu.avgGPA >2.5){
            continue;
        }

        QString info = QString("&emsp;学号:%1    姓名:%2    平均绩点:%3   &emsp;&emsp;<br>")
                .arg(stu.id)
                .arg(stu.name)
                .arg(stu.avgGPA);
        infos << info;
    }

    if(infos.isEmpty()){
        return;
    }
    infos.insert(0 ,QString("&emsp;"+app+"<br><br>"));


    showEarlyWarning(infos.join('\n'));
}
